package fr.axones.pocketagile.services.remote
{
	import com.adobe.rtc.authentication.AdobeHSAuthenticator;
	import com.adobe.rtc.events.ConnectSessionEvent;
	import com.adobe.rtc.events.SessionEvent;
	import com.adobe.rtc.session.ConnectSession;
	
	import flash.events.EventDispatcher;
	
	import fr.axones.pocketagile.ui.model.Model;
	import fr.axones.pocketagile.util.Properties;

	public class CollaborationService extends EventDispatcher
	{
		[Inject(id="model")]
		public var model:Model;
		
		private var successHandler:Function;
		private var errorHandler:Function;
		
		public var session:ConnectSession;
		public var auth:AdobeHSAuthenticator;
		
		public function CollaborationService()
		{
			auth = new AdobeHSAuthenticator();
			
			session = new ConnectSession();
			session.authenticator = auth;
			session.addEventListener(SessionEvent.SYNCHRONIZATION_CHANGE,session_synchronizationChangeHandler);
			session.addEventListener(ConnectSessionEvent.CLOSE,session_closeHandler);
			session.addEventListener(SessionEvent.ERROR,session_errorHandler);
		}				
		
		protected function session_synchronizationChangeHandler(event:SessionEvent):void
		{
			model.session = session;
			if(successHandler != null)
			{
				successHandler(event);
			}
		}
		
		protected function session_errorHandler(event:SessionEvent):void
		{
			if(errorHandler != null)
			{
				errorHandler(event);
			}
		}
		
		public function joinRoom(projectId:Number, successHandler:Function, errorHandler:Function):void
		{				
			this.successHandler = successHandler;
			this.errorHandler = errorHandler;
			
			auth.userName = Properties.adminUserName;
			auth.password = Properties.adminPassword;
			session.roomURL = Properties.roomURL;
			
			session.login();
		}
		
		public function leaveRoom():void
		{
			successHandler = null;
			errorHandler = null;
			try{
				session.logout();
			}catch(e:Error){
				
			}
		}
		
		protected function session_closeHandler(event:ConnectSessionEvent):void
		{
		}			
	}
}